﻿using System;
using System.Collections.Generic;
using Windows.UI;
using Emmellsoft.IoT.Rpi.SenseHat;
using Emmellsoft.IoT.Rpi.SenseHat.Fonts;
using Emmellsoft.IoT.Rpi.SenseHat.Fonts.SingleColor;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using RichardsTech.Sensors;

namespace IoTBlocklyHelper
{
    // The SenseHat class contains some helper functions used by the SenseHat related blocks.
    // Basically these functions are just wrappers around the great Emmellsoft.IoT.Rpi.SenseHat library,
    // which is shared at https://github.com/emmellsoft/RPi.SenseHat. For this project, we simply pulled in the NuGet reference.
    // Thanks so much for this suberb library and samples. It made creating the block implementations
    // a walk in the park :-)

    public enum SenseHatJoystickButton
    {
        None = 0x00,
        Enter = 0x01,
        Up = 0x02,
        Down = 0x04,
        Right = 0x08,
        Left = 0x10,
        Any = Enter | Up | Down | Right | Left
    }

    public sealed class SenseHat
    {
        // notice how we keep the "hat" static so that it can be reused when we stop/restart/modify the js script
        private static ISenseHat senseHat;
        private static SingleColorFont font;
        private readonly ManualResetEventSlim waitEvent = new ManualResetEventSlim(false);

        private Vector3 accel;

        public SenseHat()
        {
            try
            {
                InitSenseHat().Wait();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            // Recreate the font from the serialized bytes.
            font = SingleColorFont.Deserialize(FontBytes);
        }

        public void Clear(bool update)
        {
            if (senseHat == null) { return; }
            senseHat.Display.Clear();
            if (update)
            {
                senseHat.Display.Update();
            }
        }

        public void DrawLedMatrix(string matrix, Color foreground, int offsetX, int offsetY, bool update)
        {
            if (senseHat == null) { return; }
            if (offsetX > 7 || offsetY > 7) { return; }
            int x = offsetX;
            int y = offsetY;
            bool somethingGotUpdated = false;
            foreach (var c in matrix)
            {
                switch (c)
                {
                    case '0':
                        ++x;
                        break;
                    case '1':
                        if (x >= 0 && x < 8 && y >=0 && y < 8)
                        {
                            senseHat.Display.Screen[x, y] = foreground;
                            somethingGotUpdated = true;
                        }
                        ++x;
                        break;
                    case '|':
                        x = offsetX;
                        ++y;
                        break;
                    default:
                        ++x;
                        break;
                }
                if (y > 7) { break; }
            }
            if (somethingGotUpdated && update)
            {
                senseHat.Display.Update();
            }
        }

        public int GetAccel(int axis)
        {
            if (senseHat == null) { return 0; }
            ReadAccelerometor();
            double val = 0;
            switch (axis)
            {
                case 0:
                    val = accel.X;
                    break;
                case 1:
                    val = accel.Y;
                    break;
                case 2:
                    val = accel.Z;
                    break;
            }
            return (int)(val * 1000);
        }

        public void Print(string message, Color background, Color foreground)
        {
            if (senseHat == null) { return; }

            // Get the characters to scroll.
            IEnumerable<SingleColorCharacter> characters = font.GetChars(message);

            // Create the character renderer.
            SingleColorCharacterRenderer characterRenderer = new SingleColorCharacterRenderer(_ => foreground);

            // Create the text scroller.
            var textScroller = new TextScroller<SingleColorCharacter>(
                senseHat.Display,
                characterRenderer,
                characters);

            while (textScroller.Step())
            {
                // Draw the background.
                senseHat.Display.Fill(background);

                // Draw the scroll text.
                textScroller.Render();

                // Update the physical display.
                senseHat.Display.Update();

                // Pause for a short while.
                waitEvent.Wait(TimeSpan.FromMilliseconds(50));
            }

        }

        static DateTime barGraphHighLast = DateTime.Now;
        static int barGraphHigh = 0;

        public void PlotBarGraph(int value, int high)
        {
            if (senseHat == null) { return; }
            value = Math.Abs(value);
            high = Math.Abs(high);

            Color background = Colors.Black;
            Color foreground = Colors.Salmon;

            if (high == 0)
            {
                var now = DateTime.Now;
                if ((value > barGraphHigh) || (now - barGraphHighLast).Seconds > 5)
                {
                    barGraphHigh = value;
                    barGraphHighLast = now;
                    high = barGraphHigh;
                }
            }

            high = Math.Max(high, 32);
            var v = (value * 31) / high;
            int k = 0;
            for (int y = 7; y >= 0; --y)
            {
                for (int x = 0; x < 4; ++x)
                {
                    if (k > v)
                    {
                        senseHat.Display.Screen[3 - x, y] = background;
                        senseHat.Display.Screen[4 + x, y] = background;
                    }
                    else
                    {
                        // TODO (alecont): use more colors :-)
                        senseHat.Display.Screen[3 - x, y] = foreground;
                        senseHat.Display.Screen[4 + x, y] = foreground;
                    }
                    ++k;
                }
            }
            // Update the physical display.
            senseHat.Display.Update();
        }

        public SenseHatJoystickButton GetJoystickState(SenseHatJoystickButton mask)
        {
            if (senseHat == null) { return SenseHatJoystickButton.None; }
            senseHat.Joystick.Update();

            SenseHatJoystickButton state = SenseHatJoystickButton.None;
            if (senseHat.Joystick.EnterKey == KeyState.Pressed)
            {
                state |= SenseHatJoystickButton.Enter;
            }
            if (senseHat.Joystick.LeftKey == KeyState.Pressed)
            {
                state |= SenseHatJoystickButton.Left;
            }
            if (senseHat.Joystick.RightKey == KeyState.Pressed)
            {
                state |= SenseHatJoystickButton.Right;
            }
            if (senseHat.Joystick.UpKey == KeyState.Pressed)
            {
                state |= SenseHatJoystickButton.Up;
            }
            if (senseHat.Joystick.DownKey == KeyState.Pressed)
            {
                state |= SenseHatJoystickButton.Down;
            }

            state &= mask;

            return state;
        }

        public int GetCompassHeading()
        {
            if (senseHat == null) { return 0; }
            const double fullCircle = Math.PI * 2;

            senseHat.Sensors.ImuSensor.Update();

            if (!senseHat.Sensors.Pose.HasValue)
            {
                return -1003; // same as micro:bit (see https://m.pxt.io/reference/input/compass-heading)
            }
            double northAngle = senseHat.Sensors.Pose.Value.Z;
            if (northAngle < 0)
            {
                northAngle += fullCircle;
            }
            return ((int)(northAngle / fullCircle * 360));
        }

        public int GetTemperature()
        {
            if (senseHat == null) { return 0; }
            senseHat.Sensors.HumiditySensor.Update();
            if (!senseHat.Sensors.Temperature.HasValue)
            {
                return 0;
            }
            return (int)Math.Round(senseHat.Sensors.Temperature.Value);
        }

        public int GetHumidity()
        {
            if (senseHat == null) { return 0; }
            senseHat.Sensors.HumiditySensor.Update();
            if (!senseHat.Sensors.Humidity.HasValue)
            {
                return 0;
            }
            return (int)Math.Round(senseHat.Sensors.Humidity.Value);
        }

        public int GetPressure()
        {
            if (senseHat == null) { return 0; }
            senseHat.Sensors.PressureSensor.Update();
            if (!senseHat.Sensors.Pressure.HasValue)
            {
                return 0;
            }
            return (int)Math.Round(senseHat.Sensors.Pressure.Value);
        }

        private static IEnumerable<byte> FontBytes
        {
            get
            {
                return new byte[]
                {
                    0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x41, 0x00, 0x00, 0x7c, 0x7e, 0x0b, 0x0b, 0x7e, 0x7c,
                    0x00, 0xff, 0x00, 0x42, 0x00, 0x00, 0x7f, 0x7f, 0x49, 0x49, 0x7f, 0x36, 0x00, 0xff, 0x00, 0x43, 0x00, 0x00, 0x3e,
                    0x7f, 0x41, 0x41, 0x63, 0x22, 0x00, 0xff, 0x00, 0x44, 0x00, 0x00, 0x7f, 0x7f, 0x41, 0x63, 0x3e, 0x1c, 0x00, 0xff,
                    0x00, 0x45, 0x00, 0x00, 0x7f, 0x7f, 0x49, 0x49, 0x41, 0x41, 0x00, 0xff, 0x00, 0x46, 0x00, 0x00, 0x7f, 0x7f, 0x09,
                    0x09, 0x01, 0x01, 0x00, 0xff, 0x00, 0x47, 0x00, 0x00, 0x3e, 0x7f, 0x41, 0x49, 0x7b, 0x3a, 0x00, 0xff, 0x00, 0x48,
                    0x00, 0x00, 0x7f, 0x7f, 0x08, 0x08, 0x7f, 0x7f, 0x00, 0xff, 0x00, 0x49, 0x00, 0x00, 0x41, 0x7f, 0x7f, 0x41, 0x00,
                    0xff, 0x00, 0x4a, 0x00, 0x00, 0x20, 0x60, 0x41, 0x7f, 0x3f, 0x01, 0x00, 0xff, 0x00, 0x4b, 0x00, 0x00, 0x7f, 0x7f,
                    0x1c, 0x36, 0x63, 0x41, 0x00, 0xff, 0x00, 0x4c, 0x00, 0x00, 0x7f, 0x7f, 0x40, 0x40, 0x40, 0x40, 0x00, 0xff, 0x00,
                    0x4d, 0x00, 0x00, 0x7f, 0x7f, 0x06, 0x0c, 0x06, 0x7f, 0x7f, 0x00, 0xff, 0x00, 0x4e, 0x00, 0x00, 0x7f, 0x7f, 0x0e,
                    0x1c, 0x7f, 0x7f, 0x00, 0xff, 0x00, 0x4f, 0x00, 0x00, 0x3e, 0x7f, 0x41, 0x41, 0x7f, 0x3e, 0x00, 0xff, 0x00, 0x50,
                    0x00, 0x00, 0x7f, 0x7f, 0x09, 0x09, 0x0f, 0x06, 0x00, 0xff, 0x00, 0x51, 0x00, 0x00, 0x1e, 0x3f, 0x21, 0x61, 0x7f,
                    0x5e, 0x00, 0xff, 0x00, 0x52, 0x00, 0x00, 0x7f, 0x7f, 0x19, 0x39, 0x6f, 0x46, 0x00, 0xff, 0x00, 0x53, 0x00, 0x00,
                    0x26, 0x6f, 0x49, 0x49, 0x7b, 0x32, 0x00, 0xff, 0x00, 0x54, 0x00, 0x00, 0x01, 0x01, 0x7f, 0x7f, 0x01, 0x01, 0x00,
                    0xff, 0x00, 0x55, 0x00, 0x00, 0x3f, 0x7f, 0x40, 0x40, 0x7f, 0x3f, 0x00, 0xff, 0x00, 0x56, 0x00, 0x00, 0x1f, 0x3f,
                    0x60, 0x60, 0x3f, 0x1f, 0x00, 0xff, 0x00, 0x57, 0x00, 0x00, 0x7f, 0x7f, 0x30, 0x18, 0x30, 0x7f, 0x7f, 0x00, 0xff,
                    0x00, 0x58, 0x00, 0x00, 0x63, 0x77, 0x1c, 0x1c, 0x77, 0x63, 0x00, 0xff, 0x00, 0x59, 0x00, 0x00, 0x07, 0x0f, 0x78,
                    0x78, 0x0f, 0x07, 0x00, 0xff, 0x00, 0x5a, 0x00, 0x00, 0x61, 0x71, 0x59, 0x4d, 0x47, 0x43, 0x00, 0xff, 0x00, 0xc5,
                    0x00, 0x00, 0x70, 0x7a, 0x2d, 0x2d, 0x7a, 0x70, 0x00, 0xff, 0x00, 0xc4, 0x00, 0x00, 0x71, 0x79, 0x2c, 0x2c, 0x79,
                    0x71, 0x00, 0xff, 0x00, 0xd6, 0x00, 0x00, 0x39, 0x7d, 0x44, 0x44, 0x7d, 0x39, 0x00, 0xff, 0x00, 0xc9, 0x00, 0x00,
                    0x7c, 0x7c, 0x54, 0x56, 0x45, 0x45, 0x00, 0xff, 0x00, 0xdc, 0x00, 0x00, 0x3d, 0x7d, 0x40, 0x40, 0x7d, 0x3d, 0x00,
                    0xff, 0x00, 0x61, 0x00, 0x20, 0x74, 0x54, 0x54, 0x7c, 0x78, 0x00, 0xff, 0x00, 0x62, 0x00, 0x00, 0x7f, 0x7f, 0x48,
                    0x48, 0x78, 0x30, 0x00, 0xff, 0x00, 0x63, 0x00, 0x00, 0x38, 0x7c, 0x44, 0x44, 0x44, 0x00, 0xff, 0x00, 0x64, 0x00,
                    0x00, 0x38, 0x7c, 0x44, 0x44, 0x7f, 0x7f, 0x00, 0xff, 0x00, 0x65, 0x00, 0x00, 0x38, 0x7c, 0x54, 0x54, 0x5c, 0x18,
                    0x00, 0xff, 0x00, 0x66, 0x00, 0x00, 0x04, 0x7e, 0x7f, 0x05, 0x05, 0x00, 0xff, 0x00, 0x67, 0x00, 0x00, 0x98, 0xbc,
                    0xa4, 0xa4, 0xfc, 0x7c, 0x00, 0xff, 0x00, 0x68, 0x00, 0x00, 0x7f, 0x7f, 0x08, 0x08, 0x78, 0x70, 0x00, 0xff, 0x00,
                    0x69, 0x00, 0x00, 0x48, 0x7a, 0x7a, 0x40, 0x00, 0xff, 0x00, 0x6a, 0x00, 0x80, 0x80, 0x80, 0xfa, 0x7a, 0x00, 0xff,
                    0x00, 0x6b, 0x00, 0x00, 0x7f, 0x7f, 0x10, 0x38, 0x68, 0x40, 0x00, 0xff, 0x00, 0x6c, 0x00, 0x00, 0x41, 0x7f, 0x7f,
                    0x40, 0x00, 0xff, 0x00, 0x6d, 0x00, 0x00, 0x7c, 0x7c, 0x18, 0x38, 0x1c, 0x7c, 0x78, 0x00, 0xff, 0x00, 0x6e, 0x00,
                    0x00, 0x7c, 0x7c, 0x04, 0x04, 0x7c, 0x78, 0x00, 0xff, 0x00, 0x6f, 0x00, 0x00, 0x38, 0x7c, 0x44, 0x44, 0x7c, 0x38,
                    0x00, 0xff, 0x00, 0x70, 0x00, 0x00, 0xfc, 0xfc, 0x24, 0x24, 0x3c, 0x18, 0x00, 0xff, 0x00, 0x71, 0x00, 0x00, 0x18,
                    0x3c, 0x24, 0x24, 0xfc, 0xfc, 0x00, 0xff, 0x00, 0x72, 0x00, 0x00, 0x7c, 0x7c, 0x04, 0x04, 0x0c, 0x08, 0x00, 0xff,
                    0x00, 0x73, 0x00, 0x00, 0x48, 0x5c, 0x54, 0x54, 0x74, 0x24, 0x00, 0xff, 0x00, 0x74, 0x00, 0x00, 0x04, 0x04, 0x3f,
                    0x7f, 0x44, 0x44, 0x00, 0xff, 0x00, 0x75, 0x00, 0x00, 0x3c, 0x7c, 0x40, 0x40, 0x7c, 0x7c, 0x00, 0xff, 0x00, 0x76,
                    0x00, 0x00, 0x1c, 0x3c, 0x60, 0x60, 0x3c, 0x1c, 0x00, 0xff, 0x00, 0x77, 0x00, 0x00, 0x1c, 0x7c, 0x70, 0x38, 0x70,
                    0x7c, 0x1c, 0x00, 0xff, 0x00, 0x78, 0x00, 0x00, 0x44, 0x6c, 0x38, 0x38, 0x6c, 0x44, 0x00, 0xff, 0x00, 0x79, 0x00,
                    0x00, 0x9c, 0xbc, 0xa0, 0xe0, 0x7c, 0x3c, 0x00, 0xff, 0x00, 0x7a, 0x00, 0x00, 0x44, 0x64, 0x74, 0x5c, 0x4c, 0x44,
                    0x00, 0xff, 0x00, 0xe5, 0x00, 0x20, 0x74, 0x55, 0x55, 0x7c, 0x78, 0x00, 0xff, 0x00, 0xe4, 0x00, 0x20, 0x75, 0x54,
                    0x54, 0x7d, 0x78, 0x00, 0xff, 0x00, 0xf6, 0x00, 0x00, 0x30, 0x7a, 0x48, 0x48, 0x7a, 0x30, 0x00, 0xff, 0x00, 0xe9,
                    0x00, 0x00, 0x38, 0x7c, 0x54, 0x56, 0x5d, 0x19, 0x00, 0xff, 0x00, 0xfc, 0x00, 0x00, 0x3a, 0x7a, 0x40, 0x40, 0x7a,
                    0x7a, 0x00, 0xff, 0x00, 0x30, 0x00, 0x00, 0x3e, 0x7f, 0x49, 0x45, 0x7f, 0x3e, 0x00, 0xff, 0x00, 0x31, 0x00, 0x00,
                    0x40, 0x44, 0x7f, 0x7f, 0x40, 0x40, 0x00, 0xff, 0x00, 0x32, 0x00, 0x00, 0x62, 0x73, 0x51, 0x49, 0x4f, 0x46, 0x00,
                    0xff, 0x00, 0x33, 0x00, 0x00, 0x22, 0x63, 0x49, 0x49, 0x7f, 0x36, 0x00, 0xff, 0x00, 0x34, 0x00, 0x00, 0x18, 0x18,
                    0x14, 0x16, 0x7f, 0x7f, 0x10, 0xff, 0x00, 0x35, 0x00, 0x00, 0x27, 0x67, 0x45, 0x45, 0x7d, 0x39, 0x00, 0xff, 0x00,
                    0x36, 0x00, 0x00, 0x3e, 0x7f, 0x49, 0x49, 0x7b, 0x32, 0x00, 0xff, 0x00, 0x37, 0x00, 0x00, 0x03, 0x03, 0x79, 0x7d,
                    0x07, 0x03, 0x00, 0xff, 0x00, 0x38, 0x00, 0x00, 0x36, 0x7f, 0x49, 0x49, 0x7f, 0x36, 0x00, 0xff, 0x00, 0x39, 0x00,
                    0x00, 0x26, 0x6f, 0x49, 0x49, 0x7f, 0x3e, 0x00, 0xff, 0x00, 0x2e, 0x00, 0x00, 0x60, 0x60, 0x00, 0xff, 0x00, 0x2c,
                    0x00, 0x00, 0x80, 0xe0, 0x60, 0x00, 0xff, 0x00, 0x3f, 0x00, 0x00, 0x02, 0x03, 0x51, 0x59, 0x0f, 0x06, 0x00, 0xff,
                    0x00, 0x21, 0x00, 0x00, 0x4f, 0x4f, 0x00, 0xff, 0x00, 0x22, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x07, 0x07, 0x00,
                    0xff, 0x00, 0x23, 0x00, 0x00, 0x14, 0x7f, 0x7f, 0x14, 0x14, 0x7f, 0x7f, 0x14, 0x00, 0xff, 0x00, 0x24, 0x00, 0x00,
                    0x24, 0x2e, 0x6b, 0x6b, 0x3a, 0x12, 0x00, 0xff, 0x00, 0x25, 0x00, 0x00, 0x63, 0x33, 0x18, 0x0c, 0x66, 0x63, 0x00,
                    0xff, 0x00, 0x26, 0x00, 0x00, 0x32, 0x7f, 0x4d, 0x4d, 0x77, 0x72, 0x50, 0x00, 0xff, 0x00, 0x2d, 0x00, 0x00, 0x08,
                    0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0xff, 0x00, 0x2b, 0x00, 0x00, 0x08, 0x08, 0x3e, 0x3e, 0x08, 0x08, 0x00, 0xff,
                    0x00, 0x2a, 0x00, 0x00, 0x08, 0x2a, 0x3e, 0x1c, 0x1c, 0x3e, 0x2a, 0x08, 0x00, 0xff, 0x00, 0x3a, 0x00, 0x00, 0x66,
                    0x66, 0x00, 0xff, 0x00, 0x3b, 0x00, 0x00, 0x80, 0xe6, 0x66, 0x00, 0xff, 0x00, 0x2f, 0x00, 0x00, 0x40, 0x60, 0x30,
                    0x18, 0x0c, 0x06, 0x02, 0x00, 0xff, 0x00, 0x5c, 0x00, 0x00, 0x02, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x40, 0x00, 0xff,
                    0x00, 0x3c, 0x00, 0x00, 0x08, 0x1c, 0x36, 0x63, 0x41, 0x41, 0x00, 0xff, 0x00, 0x3e, 0x00, 0x00, 0x41, 0x41, 0x63,
                    0x36, 0x1c, 0x08, 0x00, 0xff, 0x00, 0x28, 0x00, 0x00, 0x1c, 0x3e, 0x63, 0x41, 0x00, 0xff, 0x00, 0x29, 0x00, 0x00,
                    0x41, 0x63, 0x3e, 0x1c, 0x00, 0xff, 0x00, 0x27, 0x00, 0x00, 0x04, 0x06, 0x03, 0x01, 0x00, 0xff, 0x00, 0x60, 0x00,
                    0x00, 0x01, 0x03, 0x06, 0x04, 0x00, 0xff, 0x00, 0x3d, 0x00, 0x00, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00
                };
            }
        }

        private async Task InitSenseHat()
        {
            if (senseHat == null)
            {
                senseHat = await SenseHatFactory.Singleton.GetSenseHat();
            }
        }

        private void ReadAccelerometor()
        {
            if (senseHat == null) { return; }
            if (!senseHat.Sensors.ImuSensor.Update()) { return; }
            if (!senseHat.Sensors.Acceleration.HasValue) { return; }
            accel = senseHat.Sensors.Acceleration.Value;
        }

    }
}
